package com.wx.sftp.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @author 刘畅
 * @date 2018-12-04 19:36
 */
@SuppressWarnings("unused")
public class IOUtils {
  private IOUtils() {
  }

  /**
   * 字节数组转InputStream
   *
   * @param bytes 字节数组
   * @return InputStream
   */
  @SuppressWarnings("all")
  public static InputStream bytesToInputStream(byte[] bytes) {
    return new ByteArrayInputStream(bytes);
  }

  /**
   * 字符串转InputStream
   *
   * @param str String
   * @return InputStream
   */
  public static InputStream stringToInputStream(String str) {
    return new ByteArrayInputStream(str.getBytes());
  }

  /**
   * InputStream转字节数组
   *
   * @param inputStream InputStream
   * @return 字节数组
   * @throws IOException
   */
  @SuppressWarnings("all")
  public static byte[] inputStreamToBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    byte[] buff = new byte[100];
    int rc;
    while ((rc = inputStream.read(buff, 0, 100)) > 0) {
      swapStream.write(buff, 0, rc);
    }
    return swapStream.toByteArray();
  }

  /**
   * base64编码转InputStream
   *
   * @param base64String base64形式字符串
   * @return InputStream
   */
  public static InputStream base64ToInputStream(String base64String) {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    return bytesToInputStream(bytes);
  }

  /**
   * InputStream转base64
   *
   * @param inputStream inputStream
   * @return base64 Str
   * @throws IOException IOException
   */
  public static String inputStreamToBase64(InputStream inputStream) throws IOException {
    byte[] bytes = inputStreamToBytes(inputStream);
    return Base64.getEncoder().encodeToString(bytes);
  }
}
